#coding=utf-8
from django.shortcuts import render_to_response
from app.models import *
from django.http import HttpResponse
import json
from django.shortcuts import render
from django.http import HttpResponseRedirect
import time
import tailer
from dwebsocket import require_websocket
import subprocess


def crossdomain(req):
    return render_to_response('crossdomain.xml',content_type="application/xml")

def index(req):
    #return HttpResponse('ok')
    return render_to_response('index.html')

@require_websocket
def logs(req):
    message = req.websocket.wait()
    if message == "start":
        containers=req.GET.get('sid')
        log_name=req.GET.get('log_name')
        log_line=req.GET.get('log_line')
        keyword=req.GET.get('keyword')
        #logFile="/opt/logs/"+containers+"/"+log_name
        logFile=log_name

        dict=tailer.tail(open(logFile), int(log_line))
        for i in dict:
            if keyword == "":
                req.websocket.send(i)
            else:
                if keyword in i:
                    req.websocket.send(i)
         
        for line in tailer.follow(open(logFile)):
            if keyword == "":
                req.websocket.send(line) 
            else:
                if keyword in line:
                    req.websocket.send(line)

    elif message == "stop":
        req.websocket.send('已经杀掉进程')
        req.websocket.close()
